package com.com.java8.lamdaexpression;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by User on 05/09/2014.
 */
public class Example1 {
    static Logger logger = Logger.getLogger(Example1.class.getName());

    static {
        logger.setParent(Logger.getLogger(Example1.class.getPackage().getName()));
    }

    static Map<Person, Student> data = new HashMap<Person, Student>(){{
        put(new Person("S1", "25"), new Student());
        put(new Person("S2", "26"), new Student());
    }};

    public static void main(String[] args) {
         // Not a Pure function as producing the side effects.
        mapPersonToStudents((o1, o2) -> {
            try {
                Person person = (Person) o1;
                Student student = (Student) o2;

                student.age = person.age;
                student.name = person.name;

                return true;
            } catch (Exception e) {
                logger.severe("Something bad happened at the conversion.");
                return false;
            }
        });
    }

    public static void mapPersonToStudents(Mapper m){
        for(Person person : data.keySet()){
            if(m.isMapped(person,data.get(person))){
                System.out.println("Person: " + person +" mapped to Student: "+data.get(person));
            }
        }
    }
}

interface Mapper{
    boolean isMapped(Object obj1, Object obj2);
}

class Person{
    Person(String name, String age) {
        this.name = name;
        this.age = age;
    }

    String name;
    String age;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;

        if (age != null ? !age.equals(person.age) : person.age != null) return false;
        if (name != null ? !name.equals(person.name) : person.name != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (age != null ? age.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

class Student{
    Student(String name, String age) {
        this.name = name;
        this.age = age;
    }

    Student() {
    }

    String name;
    String age;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}